<template>
  <a-cascader
    v-model="modelType"
    :options="typeDownList"
    :placeholder="placeholder"
    :fieldNames="{
      label: 'name',
      value: 'id',
      children: 'nodeList'
    }"
    allowClear
    @change="handleTypeChange"
    @popupVisibleChange="visibleChange"
  >
    <template v-if="$slots.default">
      <slot></slot>
    </template>
    <a-button v-else-if="!noSkip" type="primary" ghost>发送消息通知</a-button>
  </a-cascader>
</template>

<script>
import { SmsTypeTreeDownList } from '@/api/operations/message'
import { MemberInfoSearchVoList } from '@/api/system/system'
export default {
  props: {
    /**
     * registerList 活动
     * memberList 会员
     * userList 用户相关
     * 默认用户
     */
    dataSource: {
      type: String,
      default: 'userList'
    },
    // 默认选中
    modelValue: {
      type: Array,
      default: () => []
    },
    // 提示
    placeholder: {
      type: String,
      default: '发送消息通知'
    },
    /**
     * 业务ID,例如活动ID
     */
    objectId: {
      type: Number | String
    },
    // 为true不跳转
    noSkip: {
      type: Boolean,
      default: false
    },
    // 已勾选的smsUserIds
    selectedRowKeys: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 跳转发送消息所需用户列表 - 详情查看发送消息页面
    pageSelectedObj: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    modelValue(nval) {
      this.modelType = nval
    },
    modelType(nval) {
      this.$emit('update:modelValue', nval)
    }
  },
  data() {
    return {
      modelType: [],
      typeDownList: [],
      selectedRows: []
    }
  },
  created() {
    this.modelType = this.modelValue || []
    this.getSmsTypeDownList()
    console.log(this.$slots)
  },
  methods: {
    async getSmsTypeDownList() {
      let res = await SmsTypeTreeDownList({ dataSource: this.dataSource })
      this.typeDownList = res.data || []
    },
    // 获取发送消息所需对象
    visibleChange(visible) {
      if (!this.noSkip && visible && this.selectedRowKeys.length) {
        MemberInfoSearchVoList({
          dataSource: this.dataSource,
          userIds: this.selectedRowKeys,
          current: 1,
          size: this.selectedRowKeys.length
        }).then(res => {
          this.selectedRows = res.data.records
        })
      }
    },
    handleTypeChange(val, data) {
      this.$emit('change', val, data)
      if (this.noSkip) return
      const params = {
        dataSource: this.dataSource
      }
      if (this.objectId) {
        params.objectId = this.objectId
      }
      this.$store.commit('SET_SMSTEMPLATEOBJ', { ids: val, data })

      if (this.selectedRowKeys.length) {
        // 新封装的传参,下面方法替换完后删除
        this.$store.commit('SET_PAGESELECTEDOBJ', { 1: this.selectedRows })
      } else {
        this.$store.commit('SET_PAGESELECTEDOBJ', this.pageSelectedObj || {})
      }

      this.$router.push({
        path: '/operations/createMessage',
        query: params
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
